# Copyright (c) 2009 Stefan van der Haven
# 
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# 
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# 
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

__version__ = '0.1.0'

import urllib
import urllib2
try:
    import json
except ImportError:
    import simplejson as json

from hyves.methodgroups import METHOD_GROUPS
from hyves.oauth import OAuthSigner

class Consumer(object):
    
    API_URI = 'http://data.hyves-api.nl/'
    REQUEST_METHOD = 'POST'
    
    HA_FORMAT = 'json'
    HA_FANCYLAYOUT = 'true'
    HA_VERSION = '1.1'

    def __init__(self, consumer_key, consumer_secret):
        self._oauth_signer = OAuthSigner(consumer_key, consumer_secret)
        for group_name, group_class in METHOD_GROUPS.iteritems():
            setattr(self, group_name, group_class(self))

    def make_call(self, method_name, **kwds):
        post_data = dict(kwds)
        post_data.update({
            'ha_method': method_name,
            'ha_format' : self.HA_FORMAT,
            'ha_fancylayout': self.HA_FANCYLAYOUT,
            'ha_version': self.HA_VERSION,
        })
        post_data = self._oauth_signer.sign_request_data(
            self.API_URI, self.REQUEST_METHOD, post_data
        )
        result = '\n'.join(urllib2.urlopen(self.API_URI, urllib.urlencode(post_data)))
        return json.loads(result)

__all__ = ['__version__', 'Consumer']

